// UNFINISHED
#include<bits/stdc++.h>
using namespace std;
int s, t;
int arr[60];
int main() {
  int tc; cin>>tc;
  while(tc--) {
    memset(arr, 0, sizeof arr);
    string buf;
    cin>>buf;
    s = buf.front(), t=buf.back();
    int len = buf.size();
    for(int i=0; i<len; ++i) {
      if(buf[i]==s) {
        arr[i]=1;  //left
      }
      else if(buf[i]==t) {
        arr[i]=-1; //right
      }
    }
    for(int i=0, left=0; i<len; ++i) {
      if(arr[i]!=0)left+=arr[i];
      if(left<0) 
    }
  }
}
